package com.pay.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.constant.Constant;
import com.pay.entity.Merchant;
import com.pay.entity.MerchantAccount;
import com.pay.entity.ZfbMember;
import com.pay.exception.ServiceException;
import com.pay.mapper.MerchantMapper;
import com.pay.service.IBaseInfoService;
import com.pay.service.IMerchantAccountService;
import com.pay.service.IMerchantService;
import com.pay.service.IZfbMemberService;
import com.pay.utils.BasePage;
import com.pay.utils.FunctionUtils;
import com.pay.utils.Login;
import com.pay.utils.MD5Util;
import com.pay.utils.ResponseData;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Peng
 * @since 2018-12-06
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements IMerchantService {

	@Autowired
	private IBaseInfoService baseInfoService ;
	
	@Autowired
	private IMerchantAccountService merchantAccountService ;
	
	@Autowired
	private IZfbMemberService zfbMemberService ;
	
	@Override
	public Merchant checkLogin(Login login) {
		if(StrUtil.isBlank(login.getUsername())) {
			return null ;
		}
		if(StrUtil.isBlank(login.getPassword())) {
			return null ;
		}
		if(StrUtil.isBlank(login.getVaptcha_token())) {
			return null ;
		}
		QueryWrapper<Merchant> ew = new QueryWrapper<Merchant>();
		ew.eq("username", login.getUsername()) ;
		ew.eq("status", Constant.merchant_effective) ;
		Merchant merchant = super.getOne(ew);
		if(merchant == null) {
			return null ;
		}
		String md5Pass = MD5Util.md5Hex(login.getPassword()) ;
		if(!merchant.getPassword().equals(md5Pass)) {
			return null ;
		}
		
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("id", baseInfoService.getByKey(Constant.merchantVaptchaVID)) ; 
		map.put("secretkey", baseInfoService.getByKey(Constant.merchantVaptchaKEY)) ; 
		
		map.put("token", login.getVaptcha_token()) ;
		map.put("ip", login.getIp()) ;
		String valiResult = HttpUtil.post("http://api.vaptcha.com/v2/validate", map); //验证结果
		Integer code = JSON.parseObject(valiResult).getInteger("success");
		if(code != 1) {
			return null ;
		}
		
		return merchant ; 
	}

	@Override
	public void getList(Merchant merchant, BasePage<Merchant> page) {
		QueryWrapper<Merchant> ew = new QueryWrapper<Merchant>();
		if(page.isPage()) {
			super.page(page, ew) ;
		}else {
			List<Merchant> data = super.list(ew);
			int total = super.count(ew);
			page.setRecords(data) ;
			page.setTotal(total) ;
		}
		for (Merchant m : page.getRecords()) {
			MerchantAccount account = merchantAccountService.getByMerId(m.getId()) ;
			m.setMerchantAccount(account);
			
			ZfbMember zfbMember = zfbMemberService.getById(m.getZfbMemberId());
			m.setZfbMember(zfbMember);
		}
	}

	
	@Override
	public ResponseData doMerchantAdd(Merchant merchant) {
		if(StrUtil.isBlank(merchant.getUsername())) {
			return ResponseData.baseError("登录用户名不能为空") ;
		}
		if(merchant.getUsername().length() != 11) {
			return ResponseData.baseError("用户名必须是11位手机号码") ;
		}
		Merchant m = this.getByUsername(merchant.getUsername());
		if(m != null) {
			return ResponseData.baseError("该用户名已被注册") ;
		}
		if(StrUtil.isBlank(merchant.getPassword())) {
			return ResponseData.baseError("密码不能为空") ;
		}
		if(StrUtil.isBlank(merchant.getRemark())) {
			return ResponseData.baseError("备注不得为空") ;
		}
		if(merchant.getScale() == null) {
			return ResponseData.baseError("费率不能为空") ;
		}
		merchant.setPassword(MD5Util.md5Hex(merchant.getPassword()));
		merchant.setMerchantKey(FunctionUtils.generateUuid()) ;
		boolean result = super.save(merchant);
		
		MerchantAccount account = new MerchantAccount();
		account.setMerId(merchant.getId());
		boolean accountResult = merchantAccountService.save(account);
		
		if(result && accountResult) {
			return ResponseData.ok();
		}else {
			throw new ServiceException("添加商户失败") ;
		}
	}

	@Override
	public ResponseData doMerchantEdit(Merchant merchant) {
		if(merchant.getId() == null) {
			return ResponseData.baseError("修改失败") ;
		}
		merchant.setUsername(null); //不可修改用户名
		merchant.setPassword(merchant.getPassword() == null ? "" : merchant.getPassword());
		if(StrUtil.isBlank(merchant.getPassword())) {
			return ResponseData.baseError("密码不能为空") ;
		}
		if(StrUtil.isBlank(merchant.getRemark())) {
			return ResponseData.baseError("备注不得为空") ;
		}
		if(merchant.getScale() == null) {
			return ResponseData.baseError("费率不能为空") ;
		}
		merchant.setPassword(MD5Util.md5Hex(merchant.getPassword()));
		merchant.setMerchantKey(FunctionUtils.generateUuid()) ;
		boolean result = super.updateById(merchant);
		
		if(result) {
			return ResponseData.ok();
		}else {
			throw new ServiceException("修改商户失败") ;
		}
	}
	
	@Override
	public Merchant getByUsername(String username) {
		return super.getOne(new QueryWrapper<Merchant>().eq("username", username)) ;
	}

	@Override
	public ResponseData doMerchantSwitch(Integer id) {
		Merchant merchant = super.getById(id);
		if(merchant.getStatus() == Constant.merchant_invalid) {
			//无效变有效
			merchant.setStatus(Constant.merchant_effective);
		}else {
			//有效变无效
			merchant.setStatus(Constant.merchant_invalid);
		}
		boolean result = super.updateById(merchant) ;
		if(result) {
			return ResponseData.ok() ;
		}else {
			return ResponseData.baseError("切换状态错误") ;
		}
	}

}
